package com.nbsaas.boot.lock.impl;

import com.nbsaas.boot.lock.api.LockService;

import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class ReentrantLockService implements LockService {

    protected final ConcurrentMap<String, ReentrantLock> lockMap = new ConcurrentHashMap<>();

    @Override
    public boolean lock(String key) {
        ReentrantLock lock = lockMap.computeIfAbsent(key, k -> new ReentrantLock());
        if (lock.isLocked()) {
            return false;
        }
        lock.lock();
        return true;
    }

    @Override
    public boolean lock(String key, long timeout, TimeUnit unit) {
        ReentrantLock lock = lockMap.computeIfAbsent(key, k -> new ReentrantLock());
        try {
            // 尝试在指定时间内获取锁
            return lock.tryLock(timeout, unit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    @Override
    public boolean unlock(String key) {
        ReentrantLock lock = lockMap.get(key);
        if (lock != null && lock.isHeldByCurrentThread()) {
            lock.unlock();
            return true;
        }
        return false;
    }

    @Override
    public boolean isLocked(String key) {
        ReentrantLock lock = lockMap.get(key);
        return lock != null && lock.isLocked();
    }
}
